package com.panwenliang2008.eatwhat.ui.selectoption

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.input
import com.google.firebase.analytics.FirebaseAnalytics
import com.panwenliang2008.eatwhat.R
import com.panwenliang2008.eatwhat.data.entity.Food
import com.panwenliang2008.eatwhat.databinding.SelectOptionFragmentBinding
import com.panwenliang2008.eatwhat.utilities.InjectorUtils


class SelectOptionFragment : Fragment() {

    private val TAG = "SelectOptionFragment"

    private val selectOptionViewModel: SelectOptionViewModel by viewModels {
        InjectorUtils.provideSelectOptionViewModelFactory(this)
    }

    // [START declare_analytics]
    private var mFirebaseAnalytics: FirebaseAnalytics? = null
    // [END declare_analytics]

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(requireActivity())
        // [END shared_app_measurement]

        // [START set_current_screen]
        mFirebaseAnalytics?.setCurrentScreen(requireActivity(), TAG, null)
        // [END set_current_screen]
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = SelectOptionFragmentBinding.inflate(inflater, container, false)
        context ?: return binding.root

        val adapter = SelectOptionAdapter {
            selectOptionViewModel.delete(it)
            val bundle = Bundle()
            bundle.putString("FoodName", it.foodName.toString())
            mFirebaseAnalytics?.logEvent("DeleteFood", bundle)
        }
        binding.selectOptionList.adapter = adapter
        subscribeUi(adapter)

        //点击添加按钮跳转到添加界面
        binding.fabAdd.setOnClickListener {
            MaterialDialog(requireContext()).show {
                input { _, text ->
                    selectOptionViewModel.insert(Food(0, text.toString()))
                    val bundle = Bundle()
                    bundle.putString("FoodName", text.toString())
                    mFirebaseAnalytics?.logEvent("AddFood", bundle)
                }
                title(R.string.selectoption_message_005)
                positiveButton(R.string.selectoption_message_004)
            }
        }

        return binding.root
    }

    private fun subscribeUi(adapter: SelectOptionAdapter) {
        selectOptionViewModel.getAll().observe(viewLifecycleOwner, Observer {
            adapter.submitList(it)
        })
    }

}
